package com.lijian.service.impl;

import com.lijian.base.CodeMsg;
import com.lijian.base.Result;
import com.lijian.mapper.RoleUserMapper;
import com.lijian.mapper.UserMapper;
import com.lijian.model.SysRoleUser;
import com.lijian.model.SysUser;
import com.lijian.service.UserService;
import com.lijian.util.MD5;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Override
    public Result<SysUser> findAllUsersByPage(Integer offset, Integer limit) {
        List<SysUser> users = userMapper.findAllUsersByPage(offset, limit);
        Long count = userMapper.countAllUsers();
        return Result.success(count.intValue(), users);
    }

    @Transactional
    @Override
    public Result<SysUser> save(SysUser sysUser, Integer roleId) {

        SysUser dbUser;

        //用户名不能重复
        dbUser = userMapper.findUserByUsername(sysUser.getUsername());
        if (dbUser != null) {
            return Result.error(CodeMsg.USERNAME_REPEAT.getCode(), CodeMsg.USERNAME_REPEAT.getMessage());
        }

        //手机号不能重复
        dbUser = userMapper.findUserByPhone(sysUser.getTelephone());
        if (dbUser != null) {
            return Result.error(CodeMsg.PHONE_REPEAT.getCode(), CodeMsg.PHONE_REPEAT.getMessage());
        }

        //默认为状态为启用
        sysUser.setStatus(1);
        //sysUser.setPassword(MD5.crypt(sysUser.getPassword()));
        //改为spring security的加密方式
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());

        if (roleId != null) {
            //user表
            userMapper.save(sysUser);

            //role_user中间表
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setRoleId(roleId);
            sysRoleUser.setUserId(sysUser.getId().intValue());
            roleUserMapper.save(sysRoleUser);
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public SysUser findUserById(Long id) {
        return userMapper.findUserById(id);
    }

    @Transactional
    @Override
    public Result<SysUser> update(SysUser sysUser, Integer roleId) {
        if (roleId == null) {
            return Result.error();
        }

        //sysUser
        sysUser.setUpdateTime(new Date());
        userMapper.update(sysUser);

        //sysRoleUser
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserId(sysUser.getId().intValue());
        sysRoleUser.setRoleId(roleId);
        if (roleUserMapper.findRoleUserByUserId(sysUser.getId().intValue()) != null) {
            roleUserMapper.update(sysRoleUser);
        } else {
            roleUserMapper.save(sysRoleUser);
        }
        return Result.success();
    }

    @Transactional
    @Override
    public Result deleteById(Integer id) {
        //sysRoleUser
        roleUserMapper.deleteByUserId(id);
        //sysUser
        userMapper.deleteById(id);

        return Result.success();
    }

    @Override
    public Result<SysUser> findUserBySearch(String username, Integer offset, Integer limit) {

        int count = userMapper.findUserCountBySearch(username).intValue();
        List<SysUser> users = userMapper.findUserPageBySearch(username, offset, limit);
        return Result.success(count, users);
    }

    @Transactional
    @Override
    public Result deleteUsersByCheck(String ids) {
        //String通过","切割 转成集合
        List idList = Arrays.asList(ids.split(","));
        idList.forEach(id -> {
            //转成Integer
            Integer userId = Integer.parseInt((String) id);
            //删除sysRoleUser(外键约束。要先删中间表)
            roleUserMapper.deleteByUserId(userId);
            //删除sysUser
            userMapper.deleteById(userId);
        });
        return Result.success();
    }

    @Override
    public Result<SysUser> changePassword(String username, String oldPassword, String newPassword) {
        SysUser user = userMapper.findUserByUsername(username);
        if(user == null){
            return Result.error(1, "用户不存在");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(oldPassword, user.getPassword())){
            return Result.error(2, "旧密码输入错误");
        }
        if(oldPassword.equals(newPassword)){
            return Result.error(3, "新密码不能和旧密码一致");
        }
        userMapper.changePassword(user.getId().intValue(), new BCryptPasswordEncoder().encode(newPassword));
        return Result.success();
    }

}
